package com.qf.shop.order.interceptor;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.qf.shop.common.constants.OrderConstatns;
import com.qf.shop.common.vo.UserVo;
import com.qf.shop.order.utils.OrderUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// 动态的给订单模块设置数据源,
@Component
@Slf4j
public class OrderDynamicDatasourceInterceptor implements HandlerInterceptor {

    private ThreadLocal<Integer> tabIndexThreadLocal = new ThreadLocal<>();

    @Autowired
    private LoginInterceptor loginInterceptor;

    @Autowired
    private OrderUtils orderUtils;

    public Integer get() {
        return tabIndexThreadLocal.get();
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("进入动态设置数据源的拦截器");
        // 1.获取当前登录的用户
        UserVo userVo = loginInterceptor.get();
        setOrderDataSource(userVo);
        return true;
    }

    public void setOrderDataSource(UserVo userVo) {
        // 2.获取用户id后四位
        String lastUserId = orderUtils.getLastUserId(userVo.getId());

        int uid = Integer.parseInt(lastUserId);

        // 3.根据用户Id后四位计算数据源的编号
        Integer dbIndex = (uid % OrderConstatns.ORDER_DB_SIZE) + 1;

        // 4.设置数据源
        DynamicDataSourceContextHolder.push(OrderConstatns.ORDER_DATASOURCE_PRE + dbIndex);

        // 5.计算表的索引
        Integer tabIndex = (uid / OrderConstatns.ORDER_DB_SIZE % OrderConstatns.ORDER_TABLE_SIZE) + 1;

        tabIndexThreadLocal.set(tabIndex);

        log.debug("dbIndex:{}", dbIndex);
        log.debug("tabIndex:{}", tabIndex);
    }
}
